import { MongoClient } from 'mongodb';
import { Request, Response } from 'express';
import { Collections } from '../objects/Collections';
import { Nagget } from '../models/nagget';

export class ReadRoute {
	constructor(mongo: MongoClient) {
		this.mongo = mongo;
	}

	public async read(req: Request, res: Response) {
		const limit = Number(req.query['limit']) || 20;
		let skip;
		const rawSkip = req.query['skip'];
		if (typeof(rawSkip) == 'string') {
			if (!isNaN(Date.parse(rawSkip))) {
				skip = new Date(rawSkip);
			} else {
				skip = new Date();
			}
		} else {
			skip = new Date();
		}
		const out = await this.mongo.db().collection<Nagget>(Collections.NAGGETS).find({
			postTime: { $lte: skip }
		}).limit(limit).sort('postTime', -1).toArray();
		res.send(out);
	}

	public async find(req: Request, res: Response) {
		const filter = req.query['filter'];
		const limit = Number(req.query['limit']) || 20;
		if (typeof filter != 'string') {
			await this.read(req, res);
			return;
		} else {
			try {
				const filterObj = JSON.parse(filter);
				const out = await this.mongo.db().collection<Nagget>(Collections.NAGGETS).find(filterObj).limit(limit).toArray();
				res.send(out);
			} catch (e) {
				res.status(400);
				res.send({
					reason: 'malformed filter'
				});
			}
		}
	}

	private mongo: MongoClient;
}
